"""
@Time    :   2022/03/15 15:00:00
@Author  :   miss-tree
@Contact :   515072052@qq.com
@Description  :   数据响应格式输出
"""

from fastapi import FastAPI
from fastapi import status
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, Response, StreamingResponse
from pydantic import BaseModel
from typing import Generic, TypeVar, Optional, List, Dict, Any

T = TypeVar('T')  # 泛型类型


class ResponseModel(BaseModel, Generic[T]):
    code: int = 200
    message: str = "success"
    data: Optional[T] = None  # 可以是列表、字典或单个对象

    @classmethod
    def success(cls, data: T = None, message: str = "success")->Response:
        return cls(code=200, message=message, data=data)
    
    @classmethod
    def error(cls, code: int, message: str, data: T = None)->Response:
        return cls(code=code, message=message, data=data)
    
    @classmethod
    def forbidden(
        cls,
        msg: str = '用户无接口权限',
        data: Optional[Any] = None,
        rows: Optional[Any] = None,
        dict_content: Optional[Dict] = None,
        model_content: Optional[BaseModel] = None,
    ) -> Response:
        """
				未授权响应方法

				:param msg: 可选，自定义未授权响应信息
				:param data: 可选，未授权响应结果中属性为data的值
				:param rows: 可选，未授权响应结果中属性为rows的值
				:param dict_content: 可选，dict类型，未授权响应结果中自定义属性的值
				:param model_content: 可选，BaseModel类型，未授权响应结果中自定义属性的值
				:return: 未授权响应结果
				"""
        result = {'code': 401, 'msg': msg}
        
        if data is not None:
            result['data'] = data
        if rows is not None:
            result['rows'] = rows
        if dict_content is not None:
            result.update(dict_content)
        if model_content is not None:
            result.update(model_content.model_dump(by_alias=True))
        
        result.update({'success': False, 'time': datetime.now()})
        
        return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(result))


class ResponseList(BaseModel, Generic[T]):
    code: int = 200
    message: str = "success"
    pageIndex: int = 1
    pageSize: int = 10
    total: int = 0
    totalPage: int = 1
    data: Optional[T] = None  # 返回列表
    
    @classmethod
    def success(cls, data: T = None, message: str = "success") -> Response:
        # 兼容 dict 和 BaseModel 类型
        if isinstance(data, dict):
            _dict = data
        elif hasattr(data, '__dict__'):  # 支持 ORM 或 BaseModel 实例
            _dict = data.__dict__
        else:
            _dict = {}
        return cls(
            code=200,
            message=message,
            pageIndex= _dict.get('pageIndex',1),
            pageSize= _dict.get('pageSize',10),
            total= _dict.get('total',0),
            totalPages= _dict.get('totalPages',1),
            data=_dict.get('data',_dict if isinstance(_dict, list) else None)
        )
    
    @classmethod
    def error(cls, code: int, message: str, data: T = None) -> Response:
        return cls(code=code, message=message, data=None)
    
    @classmethod
    def forbidden(
        cls,
        msg: str = '用户无接口权限',
        data: Optional[Any] = None,
        rows: Optional[Any] = None,
        dict_content: Optional[Dict] = None,
        model_content: Optional[BaseModel] = None,
    ) -> Response:
        """
				未授权响应方法

				:param msg: 可选，自定义未授权响应信息
				:param data: 可选，未授权响应结果中属性为data的值
				:param rows: 可选，未授权响应结果中属性为rows的值
				:param dict_content: 可选，dict类型，未授权响应结果中自定义属性的值
				:param model_content: 可选，BaseModel类型，未授权响应结果中自定义属性的值
				:return: 未授权响应结果
				"""
        result = {'code': 401, 'msg': msg}
        
        if data is not None:
            result['data'] = data
        if rows is not None:
            result['rows'] = rows
        if dict_content is not None:
            result.update(dict_content)
        if model_content is not None:
            result.update(model_content.model_dump(by_alias=True))
        
        result.update({'success': False, 'time': datetime.now()})
        
        return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(result))